package com.androidplex.bucketlist.model;

import android.content.Context;
import android.nfc.NdefRecord;
import android.util.Log;
import android.widget.ArrayAdapter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by demouser on 8/14/13.
 */
public class BucketListing {

    private static final String FILENAME = "list_file";
    private static final String DELIMITER = "%%%";

    private static ArrayAdapter<BucketListItem> adapter;
    /**
     * An array of sample (dummy) items.
     */

    public static final List<BucketListItem> ITEMS = new ArrayList<BucketListItem>();

    /**
     * A map of sample (dummy) items, by ID.
     */
    public static final Map<String, BucketListItem> ITEM_MAP = new HashMap<String, BucketListItem>();

    public static void addItem(BucketListItem item) {
        //Adds the item to the current list
        ITEMS.add(item);
        ITEM_MAP.put(item.getName(), item);
        adapter.notifyDataSetChanged();
    }

    public static int getSize() {
        return ITEMS.size();
    }

    public static void updateItem(String id, BucketListItem replacement) {

        deleteItem(id);
        addItem(replacement);
        adapter.notifyDataSetChanged();
    }

    public static void setItemToDone(String id) {
        ITEM_MAP.get(id).setDone();
    }

    public static void deleteItem(String id) {
        BucketListItem old = ITEM_MAP.remove(id);
        ITEMS.remove(old);
        adapter.notifyDataSetChanged();
    }

    public static void setAdapter (ArrayAdapter<BucketListItem> a) {
        adapter = a;
    }

    public static void saveListToFile(Context context) {

        try {
            FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
            for (BucketListItem b : ITEMS) {
                fos.write(b.getName().getBytes());
                fos.write(DELIMITER.getBytes());
                fos.write(b.getDescription().getBytes());
                fos.write(DELIMITER.getBytes());
                fos.write('\n');
            }
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean loadListFromFile(Context context) {
        try {
            clearList();

            /*
              Open the internal storage for reading.
              Buffered reader is for making the output accessible line by line
              Each line represents one item in the list, formatted:

              Name%%%Description

             */
            FileInputStream fis = context.openFileInput(FILENAME);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));


            String current;
            while ((current = br.readLine()) != null) {
                //Decode and add to the list

                String parts[] = current.split("[" + DELIMITER + "]");
                addItem(new BucketListItem(parts[0], parts[3]));
            }

            br.close();
        } catch (FileNotFoundException e) {
            //If the file doesn't exist, create it for the future.
            saveListToFile(context);
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;

    }

    private static void clearList() {
        ITEMS.clear();
        ITEM_MAP.clear();
    }

    public static void delete(Context context) {
        File dir = context.getFilesDir();
        File file = new File(dir, FILENAME);
        file.delete();
    }


    public static void addEncodedItem(String s) {
        Log.i("ANDROID_BUCKET", s);
        String parts[] = s.split("[" + DELIMITER + "]");
        addItem(new BucketListItem(parts[0], parts[3]));
        Log.i("ANDROID_BUCKET", parts[0] + parts[3]);
    }
}
